package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Component
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderService orderService;
    //每分钟执行一次（下单超过15分钟还没支付的话就要修改订单状态，将其改为已取消）
    @Scheduled(cron="0 0/1 * * * ? ")
    public void  checkoutOrder(){
        log.info("订单超时，开始处理");
        //1.查询订单状态为待付款的订单，且下单时间小于当前时间减去15分钟
        LocalDateTime time = LocalDateTime.now().minusMinutes(15);
         List<Orders> ordersList= orderMapper.selectByStatusAndOrderTime(Orders.PENDING_PAYMENT,time);
        //2.修改订单状态为已取消
        if(ordersList!=null && ordersList.size()>0){
            ordersList.forEach(orders -> {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelReason("订单超时");
                orders.setOrderTime(LocalDateTime.now());
                orderMapper.update(orders);
            });
        }
    }
    //每天凌晨1点执行一次,查看是否存在待派送的订单
    @Scheduled(cron = "0 0 1 * * ? ")
    public void processDeliveryOrder(){
        log.info("开始检查待派送的订单");
        //1.查询状态为待派送的订单

        LocalDateTime time = LocalDateTime.now().minusHours(1);
       List<Orders> ordersList= orderMapper.selectProcessDeliveryOrder(Orders.CONFIRMED,time);
        //2.修改订单状态为以完成
        if(ordersList!=null && ordersList.size()>0){
            ordersList.forEach(orders -> {
                orders.setStatus(Orders.COMPLETED);
                orders.setDeliveryTime(LocalDateTime.now().minusHours(1));
                orderMapper.update(orders);
            });
        }


    }
}
